import axios from '../../utils/axios'

const app = getApp()

Component({

  options: {
    multipleSlots: true
  },

  /**
   * 组件的属性列表
   */
  properties: {
    firstShow: Boolean,
    goodsInfo: Object,
  },

  /**
   * 组件的初始数据
   */
  data: {
    lastShow: Boolean,
    applyImg: ""
  },

  /**
   * 组件的方法列表
   */
  methods: {

    // 关闭分享
    closeShareSelect: function () {
      this.setData({
        firstShow: false
      })
    },

    // 海报生成
    shareCode: function () {

      const self = this

      let canvasWidth = 0,
        canvasHeight = 0;

      const query = wx.createSelectorQuery().in(self)
      query.select('.canvas-box').boundingClientRect(function (rect) {
        console.log("rect", rect)
        canvasWidth = parseInt(rect.width)
        canvasHeight = parseInt(rect.height)
      }).exec();

      let inviter = "",
        codeImg = "",
        tempGoodsImg = "",
        tempCodeImg = "";

      axios("/personal/shareCode").then(res => {

        if (res.data.resultcode == 1) {
          inviter = res.data.result
          return inviter
        }

      }).then((result) => {

        axios('/personal/unlimit', {
          scene: "key=" + inviter + "&goodsId=" + self.data.goodsInfo.goods_id,
          page: "pages/details/details"
        }).then(res => {
          if (res.data.resultcode == 1) {
            codeImg = res.data.result
            return codeImg
          }
        }).then(() => {

          wx.showLoading({
            title: '加载中...',
            mask: true
          })

          wx.downloadFile({
            url: self.data.goodsInfo.image,
            success(res) {
              tempGoodsImg = res.tempFilePath

              wx.downloadFile({
                url: codeImg,
                success(res) {
                  tempCodeImg = res.tempFilePath

                  const ctx = wx.createCanvasContext('imgCanvas', self)

                  const grd = ctx.createLinearGradient(0, 0, canvasWidth, canvasHeight)
                  grd.addColorStop(0, "#EE864E")
                  grd.addColorStop(1, "#DC5A15")
                  ctx.setFillStyle(grd)
                  ctx.fillRect(0, 0, canvasWidth, canvasHeight)

                  ctx.drawImage('../../image/group/commodity-apply.png', canvasWidth * 0.05, canvasHeight * 0.03, canvasWidth * 0.11, canvasHeight * 0.06)
                  ctx.fillStyle = "#fff"
                  ctx.setFontSize(13)
                  ctx.fillText("小宠拼拼", canvasWidth * 0.2, canvasHeight * 0.05)
                  ctx.setFontSize(11)
                  ctx.fillText("给您推荐了", canvasWidth * 0.2, canvasHeight * 0.09)

                  ctx.drawImage(tempGoodsImg, canvasWidth * 0.04, canvasHeight * 0.12, canvasWidth * 0.92, canvasHeight * 0.5)
                  ctx.fillRect(canvasWidth * 0.04, canvasHeight * 0.62, canvasWidth * 0.92, canvasHeight * 0.35)

                  ctx.fillStyle = "#EA4353"
                  ctx.setFontSize(13)
                  ctx.fillText("团购价￥", canvasWidth * 0.08, canvasHeight * 0.67)
                  ctx.setFontSize(16)
                  ctx.fillText(self.data.goodsInfo.discount, canvasWidth * 0.25, canvasHeight * 0.67)

                  ctx.fillStyle = "#000"
                  ctx.setFontSize(14)
                  let ctxGoodsName = JSON.parse(JSON.stringify(self.data.goodsInfo.name))
                  if(ctxGoodsName.length > 23){
                    ctxGoodsName = ctxGoodsName.substring(0,20) + "..."
                  }
                  ctx.fillText(ctxGoodsName, canvasWidth * 0.08, canvasHeight * 0.72, canvasWidth * 0.8)

                  ctx.drawImage(tempCodeImg, canvasWidth * 0.15, canvasHeight * 0.73, 100, 100)
                  ctx.fillStyle = "#000"
                  ctx.setFontSize(13)
                  ctx.fillText("长按识别小程序", canvasWidth * 0.53, canvasHeight * 0.84)
                  ctx.fillStyle = "#666"
                  ctx.setFontSize(10)
                  ctx.fillText("让养宠变的更简单", canvasWidth * 0.54, canvasHeight * 0.88)

                  // 组件无法进入此方法回调，但是可以把该方法暴露出去
                  ctx.draw()

                  setTimeout(() => {
                    wx.canvasToTempFilePath({
                      width: 375,
                      height: 667,
                      destWidth: 375,
                      destHeight: 667,
                      canvasId: 'imgCanvas',
                      success(res) {
                        wx.hideLoading()
                        console.log("合成成功：", res)
                        self.setData({
                          applyImg: res.tempFilePath
                        })
                      },
                      fail(err) {
                        console.log(err)
                      }
                    }, self)
                  }, 1000)

                }
              })

            }
          })

        })

      })

    },

    // 打开生成分享海报
    shareDetails: function () {
      this.setData({
        lastShow: true
      })

      this.shareCode()

    },

    // 点击关闭分享海报
    closeModel: function () {
      this.setData({
        lastShow: false
      })
    },

    saveImage: function () {
      let that = this
      wx.getSetting({
        success(res) {
          if (!res.authSetting['scope.writePhotosAlbum'] && res.authSetting['scope.writePhotosAlbum'] != undefined) {
            wx.openSetting({
              success(res) {
                if (!res.authSetting['scope.writePhotosAlbum']) {
                  wx.showToast({
                    title: '请开启相册权限哦！',
                    icon: 'none',
                    duration: 1300
                  })
                } else {
                  that.saveCodeImg()
                }
              },
              fail(err) {
                console.log(err)
              }
            })
          } else {
            that.saveCodeImg()
          }
        }
      })

    },

    saveCodeImg() {
      let self = this
      wx.saveImageToPhotosAlbum({
        filePath: this.data.applyImg,
        success(res) {
          wx.showToast({
            title: '保存成功，可以去分享啦！',
            icon: 'none',
            duration: 1600
          })
          self.closeModel()
        },
        fail(err) {
          if (!err.errMsg.indexOf("fail cancel")) {
            wx.showToast({
              title: '请点击保存图片打开相册的权限哦！',
              icon: 'none',
              duration: 3000
            })
          }

        }
      })
    },

  }

})